package com.test.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.test.core.LoginService;
import com.test.objects.Author;

public class LoginController extends AbstractController {
	private LoginService loginService;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		String pageType = req.getParameter("page") != null ?
						req.getParameter("page") : "";
					
		if (pageType.equals("") || pageType.equals("login")){
			Map<String, Object> loginData = new HashMap<String, Object>();
			boolean isPageSubmitted = req.getMethod().equalsIgnoreCase("post");
			loginData.put("isPageSubmitted", isPageSubmitted);
			if (isPageSubmitted){
				String username = req.getParameter("username");
				String password = req.getParameter("password");
				Author author = this.loginService.checkAuthor(username, password);
				String msg = "";
				HttpSession currentSession = req.getSession();
				if (author != null){
					msg = "you have been logged in successfully as " + 
						"<a href=\"user.m?id=" + author.getId() + "\"><b>" + 
							author.getFullname() + "</b></a>";
					currentSession.setAttribute("author", author);
				}else{
					msg = "<font color=\"#ff0000\">login information incorrect!<br>" + 
						"<a href=\"login.m\">try again?</a></font>";
				}
				loginData.put("message", msg);
				loginData.put("loginSuccess", author != null);
				return new ModelAndView("login", loginData);
			}else{
				return new ModelAndView("login", loginData);
			}
		}else if (pageType.equals("reg")){
			Map<String, Object> loginData = new HashMap<String, Object>();
			String msg = "the registration is temporarily disabled";
			loginData.put("message", msg);
			return new ModelAndView("login", loginData);
		}else if (pageType.equals("logout")){
			Map<String, Object> loginData = new HashMap<String, Object>();
			HttpSession currentSession = req.getSession();
			currentSession.removeAttribute("author");
			String msg = "you have been logged out";
			loginData.put("message", msg);
			return new ModelAndView("login", loginData);
		}
		return null;
	}
	
	public void setLoginService(LoginService loginService){
		this.loginService = loginService;
	}
	
}
